/*
* form.item 上传图片组件
* 使用方式 :
*
*  <FormUpload required name='test1' label='催收信息截图' />
* */


import React from 'react'
import { Button, Upload, Form, App } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { useModel } from '@umijs/max'

const FormUpload = ({ name, label, required, text, tooltip }) => {
  const normFile = (e) => {
    return e
  }

  return (
    <Form.Item
      name={name}
      label={label}
      valuePropName='fileList'
      getValueFromEvent={normFile}
      tooltip={tooltip}
      rules={[{ required, message: `请输入${label}` }]}>
      <UploadItem label={label} text={text} />
    </Form.Item>
  )
}
const UploadItem = ({ onChange, value, label, text }) => {
  const { UPLOAD_URL } = useModel('Global')
  const { message } = App.useApp()

  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('只能上传png或jpeg格式的图片')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片不能超过2MB')
    }
    return isJpgOrPng && isLt2M
  }
  const onUploadChange = e => {
    if (e.fileList.length) {
      const list = e.fileList.filter((i) => i.value_attribute || i.response?.data?.img_url)
      onChange(list[0] ? list[0].value_attribute || list[0].response.data.img_url : '')
    } else {
      onChange('')
    }
  }

  return <>
    <Upload
      maxCount={1}
      action={UPLOAD_URL}
      accept='image/*'
      beforeUpload={beforeUpload}
      onChange={onUploadChange}
    >
      <Button icon={<UploadOutlined />}> {text || label}</Button>
    </Upload>
  </>

}

export default FormUpload
